package middleware

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

func CORS(r *ghttp.Request) {
	origin := r.Header.Get("Origin")
	if origin != "" {
		r.Response.Header().Set("Access-Control-Allow-Origin", origin)
	}
	r.Response.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
	r.Response.Header().Set("Access-Control-Allow-Headers", "*, Content-Type, Accept, Authorization")
	r.Response.Header().Set("Access-Control-Allow-Credentials", "true")

	if r.Method == "OPTIONS" {
		r.Response.WriteHeader(204)
		return
	}
	r.Middleware.Next()
}

func LogRequestParams(r *ghttp.Request) {
	// 打印请求基本信息
	g.Log().Debug(r.Context(), "Request:", r.Method, r.URL.Path)

	// 打印请求头
	g.Log().Debug(r.Context(), "Headers:", r.Header)

	// 打印所有参数
	g.Log().Debug(r.Context(), "Params:", r.GetRequestMap())

	// 打印请求体（特别是对JSON请求有用）
	g.Log().Debug(r.Context(), "Body:", r.GetBodyString())

	r.Middleware.Next()
}
